package com.candy.candyorder.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.candy.candycommon.utils.ResultBean;
import com.candy.candyorder.entity.Order;
import com.candy.candyorder.mapper.OrderMapper;
import com.candy.candyproductservice.dto.ProductDTO;
import com.candy.candyproductservice.service.ProductService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.transaction.annotation.ShardingTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Random;

/**
 * @author suYanLong
 * @version 1.0
 * @date 2023/3/21 17:27
 * @Description 描述
 */
@Slf4j
@Service
@AllArgsConstructor
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    private final ProductService productService;

    @Override
//    @GlobalTransactional(rollbackFor = Exception.class)
    @ShardingTransactionType(TransactionType.BASE)
    @Transactional(rollbackFor = Exception.class)
    public void insertBatchList() {

        Random random = new Random();
        for (int i = 0; i < 10; i++) {
            Order order = new Order();
            long userId = random.nextInt(100);
            while (userId < 10 || userId >= 100) {
                userId = random.nextInt(100);
            }
            order.setId(System.currentTimeMillis() * 100 + userId % 100);
            order.setUserId(userId);
            order.setProId(1l);
            order.setCreateTime(new Date());
//        if (i == 8) {
//                throw new RuntimeException("发送异常咯。。。。");
            baseMapper.insert(order);
//        }
//        baseMapper.insertOne(order);

            ProductDTO productDTO = new ProductDTO();
            productDTO.setId(order.getProId());
            productDTO.setSubNum(1);
            ResultBean resultBean = productService.subProduct(productDTO);
            log.info("扣减库存结果：{}", resultBean);
        }
    }

}
